<template>
	<view class="page-container home">
		<view class="title primary">通道资源数字化管理工具</view>
		<view class="content">
			<u--form labelPosition="left" :model="model1" class="login-from" ref="form1" errorType="toast">
				<u-form-item class="input-item" label="" labelWidth="0" prop="username" borderBottom ref="username">
					<u--input v-model="model1.username" placeholder="输入用户名" border="none" clearable></u--input>
				</u-form-item>
				<u-form-item class="input-item" label="" labelWidth="0" prop="password" borderBottom ref="password">
					<u--input v-model="model1.password" type="password" placeholder="输入密码" border="none"
						clearable></u--input>
				</u-form-item>
				<u-form-item label="" labelWidth="80%" ref="is_local">
					<view style="width: 68%"></view>
					<text>本地登录</text>
					<u-switch v-model="model1.is_local" size="20" activeValue="1" inactiveValue="0"
						activeColor="#407F7A"></u-switch>
				</u-form-item>
				<view></view>
			</u--form>

			<u-button :disabled="disabled" type="primary"
				@click="submit">{{ isInitializing ? '正在初始化' : '登 录' }}</u-button>
			<u-button class="login—line" :disabled="disabled" type="primary" @click="loginLine">在线登录</u-button>
		</view>
	</view>
</template>

<script>
	import CryptoJS from 'crypto-js';
	import Cookies from "js-cookie"
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import initStaticData from '@/util/initStaticData';
	import {
		selectSql
	} from '@/util/sqliteHelper.js';
	import {
		accessToken
	} from '@/util/request/accessToken.js';
	import store from '@/store/index';
	export default {
		data() {
			return {
				isInitializing: true,
				// 登录
				model1: {
					username: '',
					password: '',
					is_local: '0'
				},
				rules: {
					username: {
						type: 'string',
						required: true,
						message: '请填写用户名',
						trigger: ['blur', 'change']
					},
					password: {
						type: 'string',
						required: true,
						message: '请填写密码',
						trigger: ['blur', 'change']
					}
				}
			};
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules);
		},
		onShow() {
			if (this.$store.state.$userInfo) {
				uni.redirectTo({
					url: '/pages/index/index'
				});
			}
		},
		computed: {
			disabled() {
				let isDisabled = true;
				if (this.type) {
					if (this.model1.username && this.model1.password) {
						isDisabled = false;
					} else {
						isDisabled = true;
					}
				} else {
					if (this.model1.username && this.model1.password) {
						isDisabled = false;
					} else {
						isDisabled = true;
					}
				}
				return isDisabled;
			}
		},
		mounted() {
			initStaticData().finally(() => {
				this.isInitializing = false;
			});
		},
		methods: {
			...mapMutations(['setUserInfo']),
			loginLine() {
				// if (!this.model1.username || !this.model1.password) {
				// 	uni.showToast({
				// 		title: '用户名和密码不能为空',
				// 		icon: 'none'
				// 	});
				// 	return;
				// }
				// 使用 SHA-256 哈希密码
				const hashedPassword = CryptoJS.SHA256(this.model1.password).toString();

				// 登录请求
				uni.request({
					// url: 'http://cable.auto-sense.com.cn:19527/api/auth/signin',
					url: 'http://192.168.2.187:8080/auth/signin',
					method: 'POST',
					data: {
						username: this.model1.username,
						password: hashedPassword,
					},
					success: (res) => {
						if (res.data.status === 'SUCCESS') {
							// 登录成功，获取 acc 和 ref token
							const accessToken = res.data.result.acc; // 访问 token
							const refreshToken = res.data.result.ref; // 刷新 token
							this.$store.state.accessToken = accessToken
							uni.setStorageSync('accessToken', accessToken); // 存储访问 token
							uni.setStorageSync('refreshToken', refreshToken); // 存储访问 token
							uni.showToast({
								title: '登录成功',
								icon: 'success',
								duration: 1500 // 设置展示时间为3秒
							});
							
							// 设置跳转的时间限制
							setTimeout(() => {
								uni.redirectTo({
									url: '/pages/index/index'
									// url: '/pages/monitor/index'
								});
							}, 1000); // 1秒后跳转
						} else {
							// 登录失败，您可以根据需要添加错误信息的处理
							const errorMessage = res.errorMessage || '登录失败';
							uni.showToast({
								title: errorMessage,
								icon: 'none'
							});
						}
					},
					fail: (error) => {
						uni.showToast({
							title: '网络请求失败: ' + (error.message || '请检查网络'),
							icon: 'none',
							duration: 3000 // 设置展示时间为3秒
						});
					}
				});
			},
			submit() {
				this.$refs.form1
					.validate()
					.then(res => {
						const username = this.model1.username;
						const password = this.model1.password;
						selectSql('select * from user where usename="' + username + '"')
							.then(res => {
								console.log('login result:', res);
								const user = res[0];
								if (user && user.pwd === password) {
									this.setUserInfo({
										id: 1,
										username: this.model1.username
									});
									store.dispatch('getTreeData');
									uni.redirectTo({
										url: '/pages/index/index'
									});
								} else {
									uni.showToast({
										title: '密码错误',
										icon: 'none',
										duration: 2000
									});
								}
							})
							.catch(e => {
								uni.showToast({
									title: '登录失败',
									icon: 'none',
									duration: 2000
								});
								console.error('登录失败:', e);
							});
					})
					.catch(e => {
						console.error('表单验证不通过:', e);
					});
			}
		}
	};
</script>

<style lang="scss">
	@import '@/style/config.scss';

	uni-page-body {
		height: 100%;
	}

	.page-container {
		/* #ifndef APP-NVUE */
		margin-top: 40%;
		/* #endif */
		height: 80%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.home {
		.title {
			font-size: 1rem;
			font-weight: bold;
			margin: 1rem;
			color: #407f7a;
			margin-bottom: 4rem;
		}

		.content {
			width: 80%;
			max-width: 600px;

			.login—line {
				margin-top: 20rpx;
			}

			::v-deep button {
				border: 0;
				color: #fff;
				background: #407f7a;
				font-size: 0.8rem;

				&.u-button--disabled {
					opacity: 1;
					color: #333;
					background: #ccc;
				}
			}
		}

		.login-from {
			margin-bottom: 4rem;
			width: 100%;

			.input-item {
				height: 4rem;
			}
		}
	}
</style>